package cn.com.customer.manager.ui.customer.add

import cn.com.customer.manager.bean.AddCustomer
import cn.com.customer.manager.bean.GroupResult
import cn.com.customer.manager.bean.TagsInfo
import cn.com.customer.manager.http.BaseApi
import cn.com.customer.manager.http.subscriber.NoTipRequestSubscriber
import cn.com.customer.manager.http.subscriber.TipRequestSubscriber
import cn.com.customer.manager.manager.TokenManager
import com.google.gson.Gson
import com.xuexiang.xhttp2.XHttp
import com.xuexiang.xhttp2.XHttpProxy
import com.xuexiang.xhttp2.annotation.ThreadType
import com.xuexiang.xhttp2.subsciber.ProgressLoadingSubscriber
import com.xuexiang.xhttp2.subsciber.impl.IProgressLoader
import com.xuexiang.xupdate.utils.FileUtils

class AddCustomerPresenter constructor(view: AddCustomerContract.View) : AddCustomerContract.Presenter {
    val mView: AddCustomerContract.View = view

    override fun getTags() {
        XHttpProxy.proxy(BaseApi.Customer::class.java, ThreadType.TO_MAIN)
                .customerTagList(TokenManager.getInstance().token)
                .subscribeWith(object : TipRequestSubscriber<TagsInfo>() {
                    override fun onSuccess(t: TagsInfo?) {
                        t?.let {
                            if (it != null) {
                                mView.setTags(it.tagList)
                            }
                        }
                    }
                })
    }

    override fun addCustomer(params: AddCustomer, pathUrl: String, mIProgressLoader: IProgressLoader) {
        mIProgressLoader.updateMessage("上传中...")
        XHttp.post("customer/add")
                .keepJson(true)
                .params("data", Gson().toJson(params))
                .params("token", TokenManager.getInstance().token)
                .uploadFile("file", FileUtils.getFileByPath(pathUrl)) { bytesWritten, contentLength, done ->
                }.execute(String::class.java)
                .subscribeWith(object : ProgressLoadingSubscriber<String>(mIProgressLoader) {
                    override fun onSuccess(t: String?) {
                     mView.addSuccess()
                    }

                });
    }

    override fun getGroupList() {
        XHttpProxy.proxy(BaseApi.Customer::class.java, ThreadType.TO_MAIN)
                .customerGroupList(TokenManager.getInstance().token)
                .subscribeWith(object : NoTipRequestSubscriber<GroupResult>() {
                    override fun onSuccess(t: GroupResult?) {
                        t?.let {
                            mView.setGroupList(it)
                        }
                    }

                })
    }


    override fun start() {
        getTags()
        getGroupList()
    }
}